package com.dms.system.service;

import com.dms.common.utils.IdWorker;
import com.dms.domain.system.entity.User;
import com.dms.system.dao.UserDao;
import com.github.pagehelper.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Mr.Lgg
 * @date 2020/3/17 16:13
 */
@Service
public class UserService {
  @Autowired private UserDao userDao;

  @Autowired private IdWorker idWorke;

  public User findByUsernam(String username) {
    return userDao.findByUsername(username);
  }

  public User findById(String id) {
    return userDao.findById(id).get();
  }

  public User save(User user) {
    user.setPassword("123456");
    user.setEnableState(1);
    user.setId(idWorke.nextId() + "");
    return userDao.save(user);
  }

  public void update(User user) {
    User temp = userDao.findById(user.getId()).get();
    temp.setPassword(user.getPassword());
    temp.setUsername(user.getUsername());
    temp.setMobile(user.getMobile());
    userDao.save(temp);
  }

  public Page<User> findByPage(Map<String, Object> map, Integer pageIndex, int pageSize) {
    Specification<User> spec =
        new Specification<User>() {
          @Override
          public Predicate toPredicate(
              Root<User> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
            List<Predicate> list = new ArrayList<>();
            if (!StringUtil.isEmpty((String) map.get("companyId"))) {
              list.add(
                  criteriaBuilder.equal(
                      root.get("companyId").as(String.class), (String) map.get("companyId")));
            }
            return criteriaBuilder.and(list.toArray(new Predicate[list.size()]));
          }
        };
    Page<User> all = userDao.findAll(spec, PageRequest.of(pageIndex - 1, pageSize));
    return all;
  }

  public void deleteById(String id) {
    userDao.deleteById(id);
  }

  public List<User> findAll() {
    return userDao.findAll();
  }

  public List<String> findUserNameList() {
    List<String> list = new ArrayList<>();
    for (User user : userDao.findAll()) {
      list.add(user.getUsername());
    }
    return list;
  }
}
